package com.hps.lock;

import redis.clients.jedis.Jedis;

import java.util.UUID;

/**
 * @author heps
 * @date 2019/1/21 14:22
 */
public class RedisUtil {

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";


    static {

    }

    public boolean lock(String key, long timeout){
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        while (true) {
            String requestId = UUID.randomUUID().toString();
            String result = jedis.set(key, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, 10000);
            if (LOCK_SUCCESS.equals(result)) {
                return true;
            }
            timeout -= 100;
            if (timeout < 0) {
                break;
            }
        }
        return false;
    }

    public void unlock(String key) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.del(key);
    }

    public static void main(String[] args) {
//        ExecutorService executorService = Executors.newFixedThreadPool(10);
//        List<Integer> list = new ArrayList<>();
//        list.add(0);
//        int taskNum = 1000;
//        CountDownLatch latch = new CountDownLatch(taskNum);
//        long start = System.currentTimeMillis();
//        for (int i = 0; i < taskNum; i++) {
//            executorService.submit(() -> {
//                RedisUtil redisUtil = new RedisUtil();
//                boolean result = redisUtil.lock("testLock", 20000);
//                if (result) {
//                    Integer num = list.get(list.size() - 1);
//                    list.add(++num);
//                    redisUtil.unlock("testLock");
//                }
//                latch.countDown();
//            });
//        }
//        try {
//            latch.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(System.currentTimeMillis() - start);
//        executorService.shutdown();
//        System.out.println(list.size());
//        System.out.println(list);
    }
}
